<!-- 合同管理->开发商->新增/编辑/查看 -->
<template>
    <div class="deve-box">
        <el-breadcrumb separator="/" class="bread-title">
			<el-breadcrumb-item :to="{ path: '/developersManage' }">开发商管理</el-breadcrumb-item>
			<el-breadcrumb-item>{{pageType}}</el-breadcrumb-item>
		</el-breadcrumb>
         <p class="type-item-title">开发商信息</p>
        <el-form :rules="rules"  :model="typeForm" ref="typeForm" label-width="180px" label-position="left">
            <el-row >
                <el-col :span="11">
                    <el-form-item label="公司名称：" prop="companyName">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyName" autocomplete="off"></el-input>
                         <span v-else>{{typeForm.companyName}}</span>
                    </el-form-item>
                    <el-form-item label="纳税人识别号：" prop="companyTaxpayer">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyTaxpayer" autocomplete="off"></el-input>
                         <span v-else>{{typeForm.companyTaxpayer}}</span>
                    </el-form-item>
                    <el-form-item label="开户行名称：" prop="openingBank">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.openingBank" disabled autocomplete="off">
                            <el-button slot="append" type="primary" @click="bankShow = true">选择</el-button>
                        </el-input>
                         <span v-else>{{typeForm.openingBank}}</span>
                    </el-form-item>
                    <el-form-item label="联行号：" prop="bankNumber">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.bankNumber" disabled autocomplete="off"></el-input>
                         <span v-else>{{typeForm.bankNumber}}</span>
                    </el-form-item>
                    <el-form-item label="开户行所属省/市：" class="posterurl">
                        <div class="flex-box" v-if="typeStatus !='view'">
                             <el-form-item prop="openingBankProvince">
                                <el-input :disabled="true" v-model.trim="typeForm.openingBankProvince" placeholder="省" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item prop="openingBankCity">
                                <el-input :disabled="true" v-model.trim="typeForm.openingBankCity" placeholder="市" autocomplete="off"></el-input>
                            </el-form-item>
                        </div>
                        <span v-else>{{(typeForm.openingBankProvince ||'')+(typeForm.openingBankCity||'')}}</span>
                    </el-form-item>
                    <el-form-item label="邮政编码：" prop="companyPostalcode">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyPostalcode" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.companyPostalcode|| ''}}</span>
                    </el-form-item>
                    <el-form-item label="用途：" prop="apply">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.apply" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.apply}}</span>
                    </el-form-item>
                    <el-form-item  label="开户许可证：" class="posterurl">
                        <template  v-if="typeStatus !='view'">
                            <uploadImg @uploadSuccess="opLiceUploadSucc"  :value="this.typeForm.openingBankLicense" style="margin-top:20px;"></uploadImg>
                            <p>jpg/png/jpeg格式，大小限制在5MB以内。</p>
                        </template>
                       
                         <viewer v-else>
                             <img  :src='this.typeForm.openingBankLicense' width="100px" alt="开户许可证" />
                       </viewer>
                    </el-form-item>
                </el-col>
                 <el-col :span="2">&nbsp;</el-col>
                <el-col :span="11">
                    <el-form-item label="法定代表人：" prop="companyRepresentative">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyRepresentative" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.companyRepresentative}}</span>
                    </el-form-item>
                    <el-form-item label="开户名称：" prop="bankName">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.bankName" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.bankName}}</span>
                    </el-form-item>
                    <el-form-item label="开户账户：" prop="bankAccount">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.bankAccount" autocomplete="off"></el-input>
                        <span v-else>{{typeForm.bankAccount}}</span>
                    </el-form-item>
                    <el-form-item label="地区代码信息：" prop="bankAreaCode">
                        <el-input v-if="typeStatus !='view'" v-model='typeForm.bankAreaCode' autocomplete="off" disabled></el-input>
                        <span v-else>{{typeForm.bankAreaCode}}</span>
                    </el-form-item>
                    <el-form-item label="联系电话：" prop="companyPhone">
                        <el-input v-if="typeStatus !='view'" v-model.trim="typeForm.companyPhone" autocomplete="off" placeholder="例如“010-88888888”或者“13000000000”"></el-input>
                        <span v-else>{{typeForm.companyPhone}}</span>
                    </el-form-item>
                    <el-form-item label="公司地址：" class="posterurl">
                        <div class="flex-box" v-if="typeStatus !='view'">
                            <el-form-item prop="companyProvince">
                                <el-select v-model.trim="typeForm.companyProvince" placeholder="省" @change="loadCity(typeForm.companyProvince,'cityOptions')">
                                   <el-option v-for="(item,index) in provinceOptions" :key="index" :label="item.province" :value="item.province"> </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="companyCity">
                                <el-select v-model.trim="typeForm.companyCity" placeholder="市" @change="loadArea(typeForm.companyCity,'cityOptions')">
                                    <el-option v-for="(item,index) in cityOptions" :key="index" :label="item.city" :value="item.city"> </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="companyCounty">
                                <el-select v-model.trim="typeForm.companyCounty" placeholder="区/县">
                                    <el-option v-for="(item,index) in areaOptions" :key="index" :label="item.area" :value="item.area"> </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item style="width:100%" prop="companyAddress">
                                <el-input v-model.trim="typeForm.companyAddress" autocomplete="off"></el-input>
                            </el-form-item>
                        </div>
                        <span v-else>{{(typeForm.companyProvince || '') +(typeForm.companyCity|| '')+(typeForm.companyCounty||'')+(typeForm.companyAddress||'')}}</span>
                    </el-form-item>
                    <el-form-item label="占位" style="opacity:0">
                       
                    </el-form-item>
                    <el-form-item  label="营业执照：" class="posterurl">
                        <template  v-if="typeStatus !='view'">
                             <uploadImg @uploadSuccess="dbLiceUploadSucc" :value="this.typeForm.businessLicense" style="margin-top:20px;"></uploadImg>
                             <p>jpg/png/jpeg格式，大小限制在5MB以内。</p>
                        </template>
                       
                        <viewer v-else>
                            <img :src='this.typeForm.businessLicense' width="100px" alt="营业执照" />
                       </viewer>
                    </el-form-item>
                </el-col>
            </el-row>
		</el-form>
        
        <!-- 联系人信息 -->
        <contacts-table  :typeStatus="typeStatus" :insideId='insideId' :typeId='2' ref="contactsTable"></contacts-table>

        <p v-if="typeStatus !='view'" style="text-align:center">
            <el-button type="primary"  @click="loadApproval">发起审批</el-button>
            <el-button type="primary" v-if="typeStatus =='add'" @click="addSave(0)">保存</el-button>
            <el-button type="primary" v-if="typeStatus =='edit'" @click="editSave(0)">保存</el-button>
            <el-button type="primary"  @click="back">取消</el-button>
        </p>
        <!-- 审核记录 -> 详情页面显示 -->
        <audit-table :tableData='auditData' v-else></audit-table>
        <b-modal 
            :visible.sync='bankShow' 
            @onSave='editBank'>
        </b-modal>
    </div>
    
</template>

<script>
import api from '@/api/apiPath'
import tableList from '../common/tableList'
import uploadImg from '../common/uploadImg' //上传图片
import auditTable from '../common/auditTable' //审核记录表
import contactsTable from '../common/contactsTable' //联系人信息表
import bankBranchModal from '../common/bankBranchModal'
export default {
    components: {
        'table-list':tableList,
        'contacts-table':contactsTable,
        'audit-table':auditTable,
        'uploadImg':uploadImg,
        'b-modal':bankBranchModal
    },
	data () {
		return {
            bankShow:false,
            auditData:[],
            typeForm:{
                companyRepresentative:'',
                bankName:'',
                bankAccount:'',
                companyName:'',
                companyTaxpayer:'',
                openingBank:'',
                bankAreaCode:'',
                bankNumber:'',
                companyProvince:'',
                companyCity:'',
                companyCounty:'',
                companyCityCode:'',
                companyAddress:'',
                openingBankProvince:'',
                openingBankCity:'',
                companyPhone:'',
                companyPostalcode:'',
                apply:''
            },
            backCityOptions:[],//城市
            provinceOptions:[],//省份
            cityOptions:[],//城市
            areaOptions:[],//区
            typeStatus:"",
            pageType:"",
            insideId:'',
            typeFunction:{//页面状态
                add:()=>{
                    this.pageType = "新增";
                    this.loadprovinces();
                    },
                edit:(insideId,sort)=>{this.pageType = "编辑";
                    this.loadFromDetail(insideId,sort);//加载表单信息
                    this.loadprovinces();
                 
                },
                view:(insideId,sort)=>{ this.pageType = "详情";
                    this.loadFromDetail(insideId,sort);
                }
            },
            rules:{//验证
                companyName:[
                    {required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            if (!value) {
                                    return callback(new Error('请输入公司名称/姓名'));
                            }
                            if(value.length>30){
                                    return callback(new Error('公司名称/姓名长度不能大于30'));
                            }
                            callback();
                        }
                    }
                ],
                companyTaxpayer:[
                     { required: true, trigger: ['blur', 'change'] ,validator:(rule, value, callback)=>{
                            const reg =  /^[0-9A-Z]{15,}$/;
                            if(!value) return callback(new Error("请输入纳税人识别号"))
                            if((value.length !=15 && value.length !=17 && value.length !=18 && value.length !=20) || !reg.test(value))
                                return callback(new Error("请输入正确格式的纳税人识别号"))
                          
                            callback()
                            
                        } 
                    },
                ],
                openingBank:[
                    {required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            if (!value) {
                                    return callback(new Error('请输入开户行名称'));
                            }
                            if(value.length>30){
                                    return callback(new Error('开户行名称长度不能大于30'));
                            }
                            callback();
                        }
                    }
                ],
                bankNumber: [
                    {  required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback)=>{
                        const reg = /^\d{12}$/;
                        if(!value){
                            callback(new Error("请输入联行号"))
                        }else if(!reg.test(value)){
                             callback(new Error("请输入正确格式的联行号"))
                        }else{
                            callback()
                        }
                    }}
                ],
                bankAreaCode:[
                    { required: true, message: '请输入地区代码信息', trigger:'blur' },
                ],
                companyPhone:[
                    { required: true, trigger: ['blur', 'change'] ,validator:(rule, value, callback)=>{
                            const reg = /^0\d{2,3}-?\d{7,8}$|^1\d{10}$/;
                            if(!value){
                                callback(new Error("请输入联系电话"))
                            }else if(!reg.test(value)){
                                callback(new Error("请输入正确的联系电话"))
                            }else{
                                callback()
                            }
                        } 
                    }
                ],
                apply:[
                    {required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            if (!value) {
                                    return callback(new Error('请输入用途'));
                            }
                            if(value.length>50){
                                    return callback(new Error('用途长度不能大于50'));
                            }
                            callback();
                        }
                    }
                ],
                companyRepresentative:[
                    { required: true,  trigger: ['blur', 'change'], validator: (rule, value, callback) => {
                            if(!value) return callback(new Error("请输入法定代表人"));
                            if(value.length > 20) return callback(new Error("法定代表人长度不能大于20"));
                             callback();
                        }
                   }
                ],
                bankName:[
                    { required: true, message: '请输入开户名称', trigger:'blur' },
                    { min: 0, max: 30, message: '开户名称长度不能大于30个字符', trigger: ['blur', 'change'] }
                ],
                bankAccount: [
                    {  required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback)=>{
                         const reg = /^[0-9]\d*$/;
                        if(!value){
                            callback(new Error("请输入开户账号"))
                        }else if(!reg.test(value)){
                             callback(new Error("请输入正确格式的银行账号"))
                        }else{
                            callback()
                        }
                    }}
                ],
                companyPostalcode:[
                     {  required: false, trigger: ['blur', 'change'] ,validator: (rule, value, callback)=>{
                        const reg = /^[1-9]{6}$/;
                        if(!value)  return callback();
                        if(!reg.test(value)){
                             callback(new Error("请输入正确格式的邮政编码"))
                        }else{
                            callback()
                        }
                    }}
                ],
                companyProvince: [
                   { required: true, message: '请选择省份', trigger: 'change' }
                ],
                companyCity: [
                   { required: true, message: '请选择城市', trigger: 'change' }
                ],
                companyCounty: [
                   { required: true, message: '请选择区县', trigger: 'change' }
                ],
                companyAddress: [
                    {required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            if (!value) {
                                    return callback(new Error('请输入详细地址'));
                            }
                            if(value.length>50){
                                    return callback(new Error('长度不得超过50个字符'));
                            }
                            callback();
                        }
                    },
                   
                ],
                openingBankProvince: [
                   { required: true, message: '请选择省份', trigger: 'change' }
                ],
                openingBankCity: [
                   { required: true, message: '请选择城市', trigger: 'change' }
                ],


            },
        }
    },
    methods:{
        editBank(val){
             ({
                bankBranchName:this.typeForm.openingBank,
                cityName:this.typeForm.openingBankCity,
                provinceName:this.typeForm.openingBankProvince,
                linkNumber:this.typeForm.bankNumber,
                openCode:this.typeForm.bankAreaCode,
            } = val)
        },
        veri(){
            let contactList = this.$refs['contactsTable'].returnTabel();
            if(!contactList.length) {
                this.$alert('请添加联系人').then().catch();
                return ;
            }
            let comUrlList=['openingBankLicense','businessLicense'];
            let comText = ['请上传开户许可证','请上传营业执照'];
            let urls = comUrlList;
            let alertText = comText;
            let _this = this;
            return new Promise((resolve,reject)=>{
               this.$refs.typeForm.validate((valid)=>{
                    if(!valid){
                            resolve(false);
                            return;
                    }
                    for(let i=0;i<urls.length;i++){
                        let url = urls[i];
                        if(!_this.typeForm[url]){
                            _this.$alert(alertText[i], '提示', {
                                    type: 'error',
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        }
                            });
                            resolve(false)
                            break;
                        } 
                    }
                    resolve(true)
                })
            })
        },
        async addSave(status){
            let contactList = this.$refs['contactsTable'].returnTabel();
            let flag = await this.veri();
            if(!flag) return;
            let params = {
                businessman:this.typeForm,
                contact:contactList,
                examineStatus:status,
            }
            this.axios.post(`${api.ADDDEVMPANY}`,params).then(res => {
                    if (res.data.code == 200) {
                        this.$router.go(-1)
                        this.$message({
                            type: 'success',
                            message: status == 0?'添加成功':'已发起审核',
                        });
                    }
                })
        },
         async editSave(status){
          let flag = await this.veri();
          if(!flag) return;
          this.typeForm.examineStatus = status;
          this.axios.post(`${api.EDITDEVMPANY}`,this.typeForm).then(res => {
                if (res.data.code == 200) {
                   this.$router.go(-1)
                    this.$message({
                        type: 'success',
                        message: status == 0?'编辑成功':'已发起审核',
                    });
                }
            })
        },
        back(){
             this.$router.go(-1)
        },
        //加载当前页面表单详情
        loadFromDetail(id){
            this.axios.post(`${api.DEVMPANYDETAIL}`,{id:id}).then(res => {
                if (res.data.code == 200) {
                    let thisFrom  = res.data.data.businessmanAll;
                
                    this.typeForm = thisFrom;
                    this.contactTAbleData = res.data.data.contactList;
                    this.auditData = res.data.data.operation;
                    
                }
            })
        },
          //开户许可证上传成功
        opLiceUploadSucc(url){
        //openingBankLicense
         this.typeForm.openingBankLicense = url;
        },
        //营业执照上传成功
        dbLiceUploadSucc(url){
            //businessLicense
            this.typeForm.businessLicense = url;
        },
        //发起审批
        loadApproval(){
             if(!this.veri()) return false;
             if(this.typeStatus == 'add'){
                 this.addSave(1)
             }else{
                 this.editSave(1)
             }
        },
         //获取省
        loadprovinces(){
             this.axios.get(api.GETPROVINCES).then(res => {
                    if (res.data.code == 200) {
                       this.provinceOptions = res.data.data;
                       
                    }
                })
        },
        //获取市
        loadCity(province,options){
            let thisObj = this.provinceOptions.find(item=>{
                return province === item.province;
            })
            if(options == 'cityOptions'){
                this.$set(this.typeForm,'companyCity',null);
                this.$set(this.typeForm,'companyCounty',null);
            }else{
                this.$set(this.typeForm,'openingBankCity',null);
            }
            this.axios.get(`${api.GETCITY}/${thisObj.provinceid}`).then(res => {
                    if (res.data.code == 200) {
                       this[options] = res.data.data.cityList;
                       
                    }
                })
        },
        //获取区
        loadArea(city,options){
             let thisObj = this.cityOptions.find(item=>{
                return city === item.city;
            })
            
            if(options == 'cityOptions'){
                this.typeForm.companyCityCode = thisObj.cityId;
                this.$set(this.typeForm,'companyCounty',null);
            }
            this.axios.get(`${api.GETAREA}/${thisObj.cityId}`).then(res => {
                    if (res.data.code == 200) {
                       this.areaOptions = res.data.data.cityArealist;
                       
                    }
            })
        }

 
	
	},
	created () {
        let {pageType,insideId} = this.$route.query;
       //更改页面状态（新增/编辑/查看）
       this.typeStatus = pageType;
       this.insideId = insideId;
       //执行该状态init()
       this.typeFunction[pageType](insideId);
    },
	destroyed() {
		
	},
	filters: {

	}
}

</script>

<style lang="stylus" >
    .deve-box{
        p{
            margin:0;
            padding:20px 0;
        }
        .type-item-title{
            font-size:18px;
            color:#303133;
            font-weight :700;
            margin-bottom:30px;
            border-bottom: 1px solid #ddd;
        }
        .back-btn{
            padding:30px 0;
            text-align :center;
        }
        .flex-box{
            display:flex;
        }
        .flex-box>*{
            margin-right :10px;
        }
        .flex-box>*:last-child{
            margin-right:0;
        }
    }
    
    .posterurl .el-form-item__label:before{
        content: '*';
        color: #f56c6c;
        margin-right: 4px;
    }

</style>
